package com.example.myapplication

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.ProgressBar
import android.widget.SeekBar
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import com.example.myapplication.databinding.ActivityMainBinding
import com.example.myapplication.function.keyboard.PianoAudioManager
import com.example.myapplication.function.keyboard.PianoKeyboardView
import com.example.myapplication.function.keyboard.PianoSoundGenerator
import com.example.myapplication.function.keyboard.SimplePianoSoundGenerator


class MainActivity : AppCompatActivity() {


    private lateinit var binding: ActivityMainBinding
    private lateinit var pianoKeyboard: PianoKeyboardView
    private lateinit var pianoSoundGenerator: PianoSoundGenerator
    private lateinit var pianoAudioManager: PianoAudioManager
    private lateinit var soundGenerator: SimplePianoSoundGenerator

    // UI组件
    private lateinit var btnGenerate: Button
    private lateinit var btnLoad: Button
    private lateinit var tvStatus: TextView
    private lateinit var progressBar: ProgressBar
    private lateinit var octaveSeekBar: SeekBar
    private lateinit var volumeSeekBar: SeekBar

    // 音源库
    private var soundLibrary: Map<String, PianoSoundGenerator.PianoNote> = emptyMap()
    private var isLibraryLoaded = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        binding = ActivityMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        findViewById<Button>(R.id.to_m_m_r).setOnClickListener {
            startActivity(Intent(this, MusicModeRecognizerActivity::class.java))
        }


        initViews()
        setupPianoSystem()
    }

    private fun initViews() {
        pianoKeyboard = binding.pianoKeyboard
        btnGenerate = binding.btnGenerate
        btnLoad = binding.btnLoad
        tvStatus = binding.tvStatus
        progressBar = binding.progressBar
        octaveSeekBar = binding.octaveSeekBar
        volumeSeekBar = binding.volumeSeekBar

        // 按钮点击事件
        btnGenerate.setOnClickListener {
            generateSoundLibrary()
        }

        btnLoad.setOnClickListener {
            loadSoundLibrary()
        }

        // 八度控制
        octaveSeekBar.setOnSeekBarChangeListener(object : SeekBar.OnSeekBarChangeListener {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
                val startOctave = 1 + progress
                val endOctave = startOctave + 2 // 显示3个八度
                pianoKeyboard.setOctaveRange(startOctave, endOctave)
                updateStatus("八度范围: $startOctave - $endOctave")
            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {}
            override fun onStopTrackingTouch(seekBar: SeekBar?) {}
        })

        // 初始化八度范围
        octaveSeekBar.progress = 2 // 默认显示3-5八度
    }

    private fun setupPianoSystem() {
        pianoSoundGenerator = PianoSoundGenerator()
        soundGenerator = SimplePianoSoundGenerator()
        pianoAudioManager = PianoAudioManager(this)

        // 设置钢琴键盘回调
        pianoKeyboard.onKeyPressed = { noteName ->
            if (isLibraryLoaded) {
                pianoAudioManager.playNote(noteName, volumeSeekBar.progress / 100f)
                pianoKeyboard.pressKey(noteName)
            } else {
                showToast("请先生成或加载音源库")
            }
        }

        pianoKeyboard.onKeyReleased = { noteName ->
            pianoKeyboard.releaseAllKeys()
        }

        updateStatus("准备就绪")
    }

    private fun generateSoundLibrary() {
        progressBar.visibility = View.VISIBLE
        btnGenerate.isEnabled = false
        updateStatus("正在生成钢琴音源库...")

        // 在后台线程生成音源
        Thread {
            try {
//                soundLibrary = pianoSoundGenerator.generatePianoSoundLibrary()
                soundLibrary = soundGenerator.generateCommonSoundLibrary()

                runOnUiThread {
                    progressBar.visibility = View.GONE
                    btnGenerate.isEnabled = true
                    isLibraryLoaded = true
                    updateStatus("音源库生成完成！共 ${soundLibrary.size} 个音符")
                    showToast("音源库生成完成")

                    // 自动加载到音频管理器
                    loadSoundLibrary()
                }
            } catch (e: Exception) {
                runOnUiThread {
                    progressBar.visibility = View.GONE
                    btnGenerate.isEnabled = true
                    updateStatus("生成失败: ${e.message}")
                    showToast("生成失败")
                }
            }
        }.start()
    }

    private fun loadSoundLibrary() {
        if (soundLibrary.isEmpty()) {
            showToast("请先生成音源库")
            return
        }

        updateStatus("正在加载音源到音频系统...")
        pianoAudioManager.loadPianoSoundLibrary(soundLibrary)
        isLibraryLoaded = true
        updateStatus("音源库加载完成！可以开始弹奏")
        showToast("音源库加载完成")
    }

    private fun updateStatus(message: String) {
        tvStatus.text = message
    }

    private fun showToast(message: String) {
        Toast.makeText(this, message, Toast.LENGTH_SHORT).show()
    }

    override fun onDestroy() {
        super.onDestroy()
        pianoAudioManager.release()
    }

}